<template>
  <div>
    <el-card>
      <template #header> 账号添加 </template>
      <div>
        <el-form
          status-icon
          label-width="100px"
          class="demo-ruleForm"
          :model="fromData"
          :rules="rules"
          ref="form"
        >
          <el-form-item label="账号" prop="account">
            <el-input type="type" v-model="fromData.account"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="fromData.password"></el-input>
          </el-form-item>
          <el-form-item label="用户组" prop="userGroup">
            <el-select placeholder="请选择用户组" v-model="fromData.userGroup">
              <el-option value="超级管理员"></el-option>
              <el-option value="普通用户"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submit">提交</el-button>
            <el-button @click="$refs.form.resetFields()">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
// 解构ajax函数
import { api_users_add, api_users_repeat } from "@/api/user";
const checkAccout = async (rules, value, callback) => {
  if (!value) {
    callback(new Error("请输入账号"));
  } else if (!/^\d{6,12}$/.test(value)) {
    callback(new Error("请输入6-12位账号"));
  } else {
    let res = await api_users_repeat({
      account: value,
    });
    let { code } = res.data;
    if (code === 20) {
      callback();
    }
  }
};
const checkPassword = (rules, value, callback) => {
  if (!value) {
    callback(new Error("请输入密码"));
  } else if (!/^\d{6,12}$/.test(value)) {
    callback(new Error("请输入6-12位密码"));
  } else {
    callback();
  }
};
export default {
  data() {
    return {
      fromData: {
        account: "",
        password: "",
        userGroup: "",
      },
      rules: {
        account: [{ validator: checkAccout, trigger: "blur" }],
        password: [{ validator: checkPassword, trigger: "blur" }],
        userGroup: [{ required: true, message: "请选择用户组" }],
      },
    };
  },
  methods: {
    submit() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          // 发送请求
          let res = await api_users_add(this.fromData);
          //  解构数据
          let { code } = res.data;
          if (code === 0) {
            this.$router.push("/account/account-list");
          }
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.demo-ruleForm {
  width: 320px;
}
</style>